package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service(interfaceClass = MenuService.class)
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        PageHelper.startPage(currentPage, pageSize);

        Example example = new Example(Menu.class);
        Example.Criteria criteria = example.createCriteria();
        if (queryString != null && queryString.trim() != "") {
            criteria.orLike("name", "%" + queryString + "%");
        }

        List<Menu> list = menuMapper.selectByExample(example);

        PageInfo<Menu> pageInfo = new PageInfo<>(list);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public void add(Menu menu) {
        menuMapper.insert(menu);
    }

    @Override
    public Menu findById(Integer id) {
        Menu menu = menuMapper.selectByPrimaryKey(id);
        return menu;
    }

    @Override
    public void edit(Menu menu) {
        menuMapper.updateByPrimaryKey(menu);
    }

    @Override
    public void deleteById(Integer id) {

        Integer count = menuMapper.findCountByMenuId(id);
        if (count > 0) {
            throw new RuntimeException(MessageConstant.MENU_IS_QUOTED);
        }
        menuMapper.deleteByPrimaryKey(id);
    }
}
